Voting

: seven minus one?
(Example: nine)

The Note You're Voting On

nesk at xakep dot ru
1 year ago
I think that in some cases it makes sense to convert a Fiber to a Generator (Coroutine) for convenience. In such cases, this code will be useful:

<?php
function fiber_to_coroutine(\Fiber $fiber): \Generator
{
$index = -1; // Note: Pre-increment is faster than post-increment.
$value = null;

// Allow an already running fiber.
if (!$fiber->isStarted()) {
$value = yield ++$index => $fiber->start();
}

// A Fiber without suspends should return the result immediately.
if (!$fiber->isTerminated()) {
while (
true) {
$value = $fiber->resume($value);

// The last call to "resume()" moves the execution of the
// Fiber to the "return" stmt.
//
// So the "yield" is not needed. Skip this step and return
// the result.
if ($fiber->isTerminated()) {
break;
}

$value = yield ++$index => $value;
}
}

return
$fiber->getReturn();
}
?>

<< Back to user notes page

To Top